package com.application.api;

import com.application.common.OrderStatus;
import com.application.condition.OrderCondition;
import com.application.model.Order;
import com.application.service.OrderService;
import com.application.service.pay.OrderPojo;
import com.application.validate.OrderListValidator;
import com.application.validate.OrderTypeValidator;
import com.application.validate.OrderValidator;
import com.application.validate.UserMobileBindValidator;
import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Page;
import com.platform.annotation.Controller;
import com.platform.mvc.base.BaseController;
import com.platform.mvc.user.User;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 订单接口
 */
@Controller("/api/order")
public class OrderApiController extends BaseController {

    OrderService orderService;
    private static final Log log = Log.getLog(OrderApiController.class);

    /**
     * 订单列表（分页）
     *
     * @param status（类型：全部、待付款0、待收货1、待评价2、已取消3）
     */
    @Deprecated
    @Before(OrderListValidator.class)
    public void index() {
        int num = splitPage.getPageNumber();
        int size = splitPage.getPageSize();
        List<Integer> clientStatus = getAttr("client_status");
        Integer status = getParaToInt("status", -1);

        OrderCondition condition = new OrderCondition();
        condition.setUserid(getCUserId());
        condition.setComment(status == 2 ? 1 : 0);
        condition.setStatus(status);
        Page<Order> page = Order.dao.findList(num, size, clientStatus, condition);


        //封装客户端通用订单状态
        page.getList().forEach(o -> o.put("client_order_status", OrderStatus.clientMap.get(o.getOrder_status())));


        success(page);
    }

    /*
     * 创建订单
     * order_type 订单类型
     * module_id 类型id
     * memo: 备注 ，
     * couponId: 优惠券ID,
     * usePoint:使用积分数（固定规则：判断是否积分使用符合规则，订单金额>20元，一次最多使用1000）
     */
    @Before({OrderTypeValidator.class, UserMobileBindValidator.class})
    public void add() {
        BigDecimal orderPrice = getAttr("order_price");
        int type = getParaToInt("order_type");
        int moduleId =getParaToInt("module_id");
        Order order = orderService.createOrder(getCUser(), type, moduleId, orderPrice, 0);
        //订单创建成功，启动定时任务锁定场次
//        new OrderStatusJob().start(order.getId());
        success(order);
    }


    /**
     * 订单支付
     *
     * @param orderId
     * @param payType 支付类别,「0 余额支付 | 1微信 | 2支付宝 |4小程序」
     * @param payPass 可选,余额支付时使用(明文)
     * @param openid  可选，小程序支付使用
     * @return
     */
    @Before(OrderValidator.class)
    public void pay() {
        int payType = getParaToInt("payType");
        Order order = getAttr("order");
        String clientIp = getAttrForStr("clientIp");
        User user = super.getCUser();
        Map<String, Object> map = null;
        try {
            String openid = user.get("openid");
            OrderPojo pojo = new OrderPojo(order, user, getPara("payPass"), clientIp, openid);
            map = orderService.pay(payType, pojo);
            success(map);
        } catch (Exception e) {
            e.printStackTrace();
            String msg = "支付失败";
            if (StrKit.notBlank(e.getMessage())) {
                msg = e.getMessage();
            }
            error(500, msg);
        }
    }

    /*
    订单详情
    param:id
     */
    public void view() {
        Order order = Order.dao.findDetail(getParaToInt() == null ? getParaToInt("id") : getParaToInt());
        success(order);
    }

    /**
     * 订单删除
     * 需登录，已完成、待评价、已取消的订单可以删除，做假删除处理，不删除数据
     *
     * @param id
     * @return 是否成功
     */
    public void del() {
        int userId = getCUserId();
        Order order = Order.dao.findById(getPara("id"));
        if (order.getOrder_userid() != userId) {
            error(400, "权限认证失败");
            return;
        }

        order.setDelete_time(getDate());
        order.setDelete_userid(userId);
        boolean f = order.update();
        if (f) {
            success(1);
        } else {
            error(500, "删除失败");
        }
    }

    /**
     * 取消订单
     * 待付款的订单可以取消，其他的不可以
     *
     * @param id, desc申请理由
     * @return 是否成功
     */
    @Deprecated
    public void cancel() {
        boolean f = Order.dao.cancel(getParaToInt("id"), getPara("desc"), getCUserId(), OrderStatus.CLOSED_CANCEL);
        if (f) {
            success(1);
        } else {
            error(500, "取消失败");
        }
    }

    /**
     * 订单申请退款
     * 提交申请退款后，状态变为退款中，有后台处理统一退款后才可退款成功
     *
     * @param id, desc申请理由
     * @return 是否成功
     */
    @Deprecated
    public void applyRefund() {
        boolean f = Order.dao.applyRefund(getParaToInt("id"), getPara("desc"), getCUserId());
        if (f) {
            success(1);
        } else {
            error(500, "申请退款失败");
        }
    }

    /**
     * 评价订单
     *
     * @param 订单ID 评价内容 content
     *             images 图片,多个逗号分割：0~9张
     *             is_annon 是否匿名;0：实名；1：匿名
     *             star:评分几颗星
     * @return 是否成功
     */
    @Deprecated
//    @Before(OrderValidator.class)
    public void comment() {
        boolean f = Order.dao.comment(getCUserId(), getParaToInt("id"), getParamMap());
        if (f) {
            success(1);
        } else {
            error(500, "评论失败");
        }
    }

}
